package com.example.power_service.controller;

import com.example.power_service.jwt.JWTUtils;
import com.example.power_service.return_data.Mall_Data;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Api(tags = "鉴权中心")
@RestController("/power")
public class AcsController
{

    @Autowired
    JWTUtils jwtUtils;

    /**
     * 授权
     */
    @ApiOperation("授权，颁发token")
    @RequestMapping("/authorization")
    public Mall_Data authorization(@ApiParam("用户id")@RequestParam("userid")int userid, HttpServletResponse response){
        //返回数据实体类
        Mall_Data res=new Mall_Data();

        //颁发token,并且保存在浏览器cookie中
        Cookie cookie = new Cookie("token", jwtUtils.createtoken(userid));
        cookie.setMaxAge(3600);
        cookie.setDomain("localhost");
        cookie.setPath("/");
        response.addCookie(cookie);


            //设置状态码
            res.setcode(200);
            //设置error信息
            res.seterror("not error");
            //设置数据信息
            res.setdata("颁发成功");

        return res;
    }

    /**
     * 鉴权
     */
    @ApiOperation("鉴定token")
    @RequestMapping("/checkAcs")
    public Mall_Data checkAcs(@RequestParam("token") String token,HttpServletResponse response){
        //返回数据实体类
        Mall_Data res=new Mall_Data();


        //验证token
        Map map=jwtUtils.checktoken(token);
       if (!(boolean)map.get("path")){
           res.setcode(520).seterror((String)map.get("data"));
           return res;
       }
       //token 快过期，重新颁发token
       if (!map.get("data").equals("token Validation succeeded !")){
           authorization((int)map.get("data"),response);
       }
        //设置状态码
        res.setcode(200);
        //设置error信息
        res.seterror("not error");
        //设置数据信息

        res.setdata("颁发成功");

        return res;
    }



}
